package com.link.base.base.mpconfig.service;

import com.alibaba.fastjson.JSONObject;
import com.link.base.sms.model.Template;
import com.link.base.user.model.CoreUser;
import com.link.base.base.mpconfig.dao.mybatis.mapper.MpMapper;
import com.link.base.base.mpconfig.dao.mybatis.mapper.MpTemplateMapper;
import com.link.base.base.mpconfig.dao.mybatis.mapper.SendTempMessageMapper;
import com.link.base.base.mpconfig.model.Mp;
import com.link.base.base.mpconfig.model.SendTempMessage;
import com.link.base.base.mpconfig.model.TemplateData;
import com.link.base.base.sms.model.PushSms;
import com.link.base.base.sms.service.PushSmsService;
import com.link.base.base.user.service.UserService;
import com.link.base.base.wechat.dao.mybatis.mapper.TableMapper;
import com.link.base.base.wechat.model.TemTable;
import com.link.core.cllog.LCLogger;
import com.link.base.wechat.basic.util.WeixinHttpUtil;
import com.link.base.wechat.thirdparty.util.WxThirdPartyUtil;
import com.link.base.wechat.wxplatform.dao.mybatis.mapper.WxPlatformMapper;
import com.link.base.wechat.wxplatform.model.WxPlatform;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.interceptor.SecurityInterceptor;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.*;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.*;

/**
 * 发送模板消息
 *
 * @author: 闫有霞
 * @date: 2019/12/19
 */
@Service
public class SendTempMessageServiceImpl extends BasicServiceImpl<SendTempMessage> implements SendTempMessageService {

    @Resource
    private SendTempMessageMapper sendTempMessageMapper;

    @Resource
    private MpTemplateMapper mpTemplateMapper;

    @Resource
    private WxPlatformMapper wxPlatformMapper;

    @Resource
    private MpMapper mpMapper;

    @Resource
    private TableMapper tableMapper;

    @Resource
    private PushSmsService pushSmsService;

    @Resource
    private MpTokenService mpTokenService;

    @Resource
    private UserService userService;

    @Resource
    private Environment env;

    @Override
    public BasicMapper<SendTempMessage> getBasicMapper() {
        return sendTempMessageMapper;
    }

    /**
     *@createdBy 闫有霞
     *@date 2018/12/14
     *@methods: getParams
     *@param: String tempRowId  模板记录ID
     *@return: sendTempMessage  发送模板信息参数对象
     *@description: 获取发送模板信息的参数
     **/
    @Override
    public SendTempMessage getParams(SendTempMessage entity) throws Exception {
        Long tempRowId = entity.getTempRowId();
        String type = entity.getType();
        Long parentId = entity.getParentId();
        String parentType = entity.getParentType();
        /**根据模板记录ID 获取模板对象*/
        SendTempMessage sendTempMessage = new SendTempMessage();
        String WeChat = "WeChat";
        String MP = "MP";
        List<String> param = new ArrayList<>();
        Template template = new Template();
        template.setId(tempRowId);
        template = mpTemplateMapper.queryById(template);
        sendTempMessage.setTemplateId(template.getTemplateId());
        String pageUrl = template.getAttr3() + "?id=" + parentId;
        sendTempMessage.setPageUrl(pageUrl);
        /**判断模板信息类型获取appId 及 appSecret*/
        if (WeChat.equals(type)) {
            WxPlatform platform = new WxPlatform();
            platform.setId(Long.parseLong(template.getWxId()));
            platform = wxPlatformMapper.queryById(platform);
            sendTempMessage.setAppId(platform.getWx_app_id());
            if (StringUtils.isNotBlank(template.getFirst())) {
                param.add(template.getFirst());
            }
            if (StringUtils.isNotBlank(template.getParameter1())) {
                SendTempMessage paramValue = new SendTempMessage();
                paramValue.setParamId(Long.parseLong(template.getParameter1()));
                paramValue.setParentType(parentType);
                paramValue.setParentId(parentId);
                String value = this.getParaValue(paramValue);
                param.add( filterStr(value));
            }
            if (StringUtils.isNotBlank(template.getParameter2())) {
                SendTempMessage paramValue = new SendTempMessage();
                paramValue.setParamId(Long.parseLong(template.getParameter2()));
                paramValue.setParentType(parentType);
                paramValue.setParentId(parentId);
                String value = this.getParaValue(paramValue);
                param.add(filterStr(value));
            }
            if (StringUtils.isNotBlank(template.getParameter3())) {
                SendTempMessage paramValue = new SendTempMessage();
                paramValue.setParamId(Long.parseLong(template.getParameter3()));
                paramValue.setParentType(parentType);
                paramValue.setParentId(parentId);
                String value = this.getParaValue(paramValue);
                param.add(filterStr(value));
            }
            if (StringUtils.isNotBlank(template.getParameter4())) {
                SendTempMessage paramValue = new SendTempMessage();
                paramValue.setParamId(Long.parseLong(template.getParameter4()));
                paramValue.setParentType(parentType);
                paramValue.setParentId(parentId);
                String value = this.getParaValue(paramValue);
                param.add(filterStr(value));
            }
            if (StringUtils.isNotBlank(template.getParameter5())) {
                SendTempMessage paramValue = new SendTempMessage();
                paramValue.setParamId(Long.parseLong(template.getParameter5()));
                paramValue.setParentType(parentType);
                paramValue.setParentId(parentId);
                String value = this.getParaValue(paramValue);
                param.add(filterStr(value));
            }
            if (StringUtils.isNotBlank(template.getRemark())) {
                param.add(template.getRemark());
            }


        } else if (MP.equals(type)) {
            Mp mp = new Mp();
            mp.setId(Long.parseLong(template.getWxId()));
            mp = mpMapper.queryById(mp);
            sendTempMessage.setAppId(mp.getAppId());
            sendTempMessage.setAppSecret(mp.getAppSecret());
            if (StringUtils.isNotBlank(template.getParameter1())) {
                SendTempMessage paramValue = new SendTempMessage();
                paramValue.setParamId(Long.parseLong(template.getParameter1()));
                paramValue.setParentType(parentType);
                paramValue.setParentId(parentId);
                String value = this.getParaValue(paramValue);
                param.add(filterStr(value));
            }
            if (StringUtils.isNotBlank(template.getParameter2())) {
                SendTempMessage paramValue = new SendTempMessage();
                paramValue.setParamId(Long.parseLong(template.getParameter2()));
                paramValue.setParentType(parentType);
                paramValue.setParentId(parentId);
                String value = this.getParaValue(paramValue);
                param.add(filterStr(value));
            }
            if (StringUtils.isNotBlank(template.getParameter3())) {
                SendTempMessage paramValue = new SendTempMessage();
                paramValue.setParamId(Long.parseLong(template.getParameter3()));
                paramValue.setParentType(parentType);
                paramValue.setParentId(parentId);
                String value = this.getParaValue(paramValue);
                param.add(filterStr(value));
            }
            if (StringUtils.isNotBlank(template.getParameter4())) {
                SendTempMessage paramValue = new SendTempMessage();
                paramValue.setParamId(Long.parseLong(template.getParameter4()));
                paramValue.setParentType(parentType);
                paramValue.setParentId(parentId);
                String value = this.getParaValue(paramValue);
                param.add(filterStr(value));
            }
            if (StringUtils.isNotBlank(template.getParameter5())) {
                SendTempMessage paramValue = new SendTempMessage();
                paramValue.setParamId(Long.parseLong(template.getParameter5()));
                paramValue.setParentType(parentType);
                paramValue.setParentId(parentId);
                String value = this.getParaValue(paramValue);
                param.add(filterStr(value));
            }
            if (StringUtils.isNotBlank(template.getParameter6())) {
                SendTempMessage paramValue = new SendTempMessage();
                paramValue.setParamId(Long.parseLong(template.getParameter6()));
                paramValue.setParentType(parentType);
                paramValue.setParentId(parentId);
                String value = this .getParaValue(paramValue);
                param.add(filterStr(value));
            }

        }
        sendTempMessage.setParams(param);
        return sendTempMessage;
    }

    /**
     *@createdBy 闫有霞
     *@date 2018/12/14
     *@methods: getParaValue
     *@param: String paramId   参数记录ID
     *@return: String value
     *@description: 获取参数具体值
     **/
    @Override
    public String getParaValue(SendTempMessage entity) throws Exception {
        Long paramId = entity.getParamId();
        Long parentId = entity.getParentId();
        String parentType = entity.getParentType();
        String value = "";
        /**订单*/
        String ORDER = "order";
        /**优惠券记录*/
        String COUPINREC = "couponrec";
        /**离店报告*/
        String REPORT = "report";
        /**登录报告*/
        String APPLOGIN = "applogin";
        /**地址*/
        String ADDRESS = "ADDRESS";
        /**订单状态*/
        String ORDERSTATUS = "STATUS";
        /**APP登录应用类型*/
        String LOGINSYSTEM = "SYSTEM";
        /**查询门店表*/
        String STORE = "Store";
        /**获取门店的id*/
        Long lnkStoreId = Long.parseLong(RedisUtil.getCommonProperty("lnkStoreId"));
        /**查询会员交易表*/
        String TRANSAC = "transac";
        /**根据参数记录ID 查到 表名 和 列名*/
        TemTable temTable = new TemTable();
        temTable.setId(paramId);
        temTable = tableMapper.queryById(temTable);
        /**调以order为基准获取值的方法*/
        TemTable paraTable = new TemTable();
        paraTable.setId(parentId);
        String  table1 = temTable.getTable1();
        paraTable.setTable1(table1);
        /**去除列名中开头的数字*/
        String column1 = temTable.getColumn1().replaceFirst("\\d+","");
        paraTable.setColumn1(column1);
        /**判断触发发送模板信息对象类型*/
        if (ORDER.equals(parentType)) {
            /**判断要获取字段是否是地址*/
            if (ADDRESS.equals(column1)) {
                value = sendTempMessageMapper.queryAddressVauleByOrder(paraTable);
            } else if (ORDERSTATUS.equals(column1)) {
                value = sendTempMessageMapper.queryListVauleByOrder(paraTable);
            } else if (STORE.equals(table1)) {
                paraTable.setId(lnkStoreId);
                value = sendTempMessageMapper.queryValueByStore(paraTable);
            } else {
                value = sendTempMessageMapper.queryVauleByOrder(paraTable);
            }

        } else if (COUPINREC.equals(parentType)) {
            /**调以couponrec为基准获取值的方法*/
            value = sendTempMessageMapper.queryVauleByCoupRec(paraTable);
        } else if (REPORT.equals(parentType)) {
            value = sendTempMessageMapper.queryVauleByDepartureReport(paraTable);
        } else if (APPLOGIN.equals(parentType)) {
            if (LOGINSYSTEM.equals(column1)) {
                String  source = sendTempMessageMapper.queryVauleByAppLogin(paraTable);
                value = LovUtil.getLovName("APP_LOGIN_TYPE",source);

            } else {
                value = sendTempMessageMapper.queryVauleByAppLogin(paraTable);
            }

        } else if (TRANSAC.equals(parentType)) {
            value = sendTempMessageMapper.queryVauleByTransac(paraTable);
        }
        return value;
    }

    /**
     * @createdBy 闫有霞
     * @date 2018/12/14
     * @methods: queryVauleByOrder
     * @param: temTable
     * @return: String value
     * @description: 以订单表为基准获取参数值
     **/
    @Override
    public String queryVauleByOrder(TemTable temTable) throws Exception {
        return sendTempMessageMapper.queryVauleByOrder(temTable);
    }

    /**
     * @createdBy 闫有霞
     * @date 2018/12/14
     * @methods: queryVauleByOrder
     * @param: temTable
     * @return: String value
     * @description: 以优惠券领取表为基准获取参数值
     **/
    @Override
    public String queryVauleByCoupRec(TemTable temTable) throws Exception {
        return sendTempMessageMapper.queryVauleByCoupRec(temTable);
    }
    /**
     * @createdBy 闫有霞
     * @date 2018/12/17
     * @methods: sendMpTemplate
     * @param: sendTempMessage
     * @return:  JSONObject
     * @description: 发送小程序模板信息
     **/

    @Override
    public JSONObject sendMpTemplate(SendTempMessage entity) throws Exception {
        Mp mp = new Mp();
        mp.setAppId(entity.getAppId());
        mp.setAppSecret(entity.getAppSecret());
        String accesstoken = mpTokenService.getMpAccessToken(mp);
        JSONObject paramJson = new JSONObject();
        // 将参数写入到paramJson对象中
        paramJson.put("touser",entity.getOpenId());
        paramJson.put("template_id",entity.getTemplateId());
        paramJson.put("form_id",entity.getFormId());
        if (!StringUtils.isNull(entity.getPageUrl())) {
            paramJson.put("page",entity.getPageUrl());
        }
        if (entity.getParams().size() != 0 ) {
            Map<String, TemplateData> m = new HashMap<>();
            for (int i = 0 ;i < entity.getParams().size();i++) {
                TemplateData keyword = new TemplateData();
                keyword.setValue(entity.getParams().get(i));
                Integer key = i + 1;
                m.put("keyword" + key,keyword);
            }
            paramJson.put("data",m);
        }
        String data = JsonUtil.toString(paramJson);
        String requestUrl = env.getProperty("weixinuri.sendTempMessageUrl").replace("ACCESS_TOKEN", accesstoken);
        JSONObject json = WeixinHttpUtil.httpRequest(requestUrl, "POST", data);
        json.put("param", data);
        return json;
    }
    /**
     * @createdBy 闫有霞
     * @date 2018/12/17
     * @methods: sendMpTemplate
     * @param: sendTempMessage
     * @return:  JSONObject
     * @description: 发送微信模板信息
     **/

    @Override
    public JSONObject sendWxTemplate(SendTempMessage entity) throws Exception {
        // 获取token
        String accessToken = WxThirdPartyUtil.getAccessToken(entity.getAppId()).get("authorizer_access_token");
        JSONObject paramJson = new JSONObject();
        // 将参数写入到paramJson对象中
        paramJson.put("touser",entity.getOpenId());
        paramJson.put("template_id",entity.getTemplateId());
        if (entity.getParams().size() != 0 ) {
            Map<String, TemplateData> m = new HashMap<>();
            for (int i = 0 ;i < entity.getParams().size();i++) {
                TemplateData keyword = new TemplateData();
                keyword.setValue(entity.getParams().get(i));
                if ( i == 0) {
                    m.put("first",keyword);
                } else if ( i == entity.getParams().size() - 1 ) {
                    m.put("remark",keyword);
                } else {
                    Integer key = i;
                    m.put("keyword" + key,keyword);
                }
            }
            paramJson.put("data",m);
        }
        String data = JsonUtil.toString(paramJson);
        // 发送地址
        String requestUrl = env.getProperty("weixinuri.wxTempLateMsgUrl").replace("ACCESS_TOKEN", accessToken);
        JSONObject json =  WeixinHttpUtil.httpRequest(requestUrl, "POST", data);
        json.put("param", data);
        return json;
    }

    /**
     * @createdBy 闫有霞
     * @date 2018/12/17
     * @methods: getWxOpenIdByCoupRec
     * @param: entity
     * @return: String openId
     * @description: 通过订单记录ID获取openId
     **/

    @Override
    public String getWxOpenIdByOrder(SendTempMessage entity) throws Exception {
        return sendTempMessageMapper.getWxOpenIdByOrder(entity);
    }
    /**
     * @createdBy 闫有霞
     * @date 2018/12/17
     * @methods: getWxOpenIdByCoupRec
     * @param: entity
     * @return: String openId
     * @description: 通过优惠券记录ID获取openId
     **/

    @Override
    public String getWxOpenIdByCoupRec(SendTempMessage entity) throws Exception {
        return sendTempMessageMapper.getWxOpenIdByCoupRec(entity);
    }
    /**
     * @createdBy 闫有霞
     * @date 2018/12/15
     * @methods: filterStr
     * @param:  String
     * @return:  String
     * @description: 过滤字符串转化为指定格式
     **/

    @Override
    public String filterStr(String str) throws Exception {
        String newStr = "";
        /**如果str不为空*/
        if (StringUtils.isNotBlank(str)) {
            /**如果字符串格式为日期类型的*/
            if (str.contains(":")) {
                newStr = str.substring(0,str.length() - 2);
            /**如果字符串格式为小数的*/
            } else if (str.contains(".")) {
                newStr = str.substring(0,str.indexOf(".") + 3).concat("元");
            } else {
                newStr = str;
            }
        } else {
            newStr = "无";
        }
        return newStr;
    }

    /**
     * @createdBy 闫有霞
     * @date 2018/12/14
     * @methods: queryVauleByOrder
     * @param: temTable
     * @return: String value
     * @description: 以订单表为基准获取地址类型参数值
     **/

    @Override
    public String queryAddressVauleByOrder(TemTable temTable) throws Exception {
        return sendTempMessageMapper.queryAddressVauleByOrder(temTable);
    }

    @Override
    public String queryVauleByDepartureReport(TemTable temTable) throws Exception {
        return sendTempMessageMapper.queryVauleByDepartureReport(temTable);
    }

    @Override
    public String queryVauleByAppLogin(TemTable temTable) throws Exception {
        return sendTempMessageMapper.queryVauleByAppLogin(temTable);
    }

    @Override
    public String queryListVauleByOrder(TemTable temTable) throws Exception {
        return sendTempMessageMapper.queryListVauleByOrder(temTable);
    }

    @Override
    public String getWxOpenIdByDepartureReport(SendTempMessage entity) throws Exception {
        return sendTempMessageMapper.getWxOpenIdByDepartureReport(entity);
    }

    @Override
    public String getWxOpenIdByAppLogin(SendTempMessage entity) throws Exception {
        return sendTempMessageMapper.getWxOpenIdByAppLogin(entity);
    }


    /**
     *@createdBy 闫有霞
     *@date 2018/12/29
     *@methods: getMessageFormId
     *@param: String openId 当前登录人的openId
     *@return: String formId
     *@description:  获取保存到redis的formId
     **/
    @Override
    public String getMessageFormId(String openId) throws Exception {
        LinkRedisClient jedis = null;
        String formId = "";
        try {
            jedis = RedisUtil.getJedis();
            Set<String>  messageFormKeySet = jedis.keys("MESSAGE_FORM_ID:" + openId + ":*");
            if ( !messageFormKeySet.isEmpty()) {
                String key = messageFormKeySet.iterator().next();
                formId = jedis.get(key);
                jedis.del(key);
            } else {
                throw new ServiceException("MPCONFIG-006");
            }

        } catch (Exception e) {
            LCLogger.withException(e);
        } finally {
            RedisUtil.returnResource(jedis);
        }
        return formId;
    }


    @Override
    public String queryValueByStore(TemTable temTable) throws Exception {
        return sendTempMessageMapper.queryValueByStore(temTable);
    }

    @Override
    public String queryVauleByTransac(TemTable temTable) throws Exception {
        return sendTempMessageMapper.queryVauleByTransac(temTable);
    }

    @Override
    public String getWxOpenIdByTransac(SendTempMessage entity) throws Exception {
        return sendTempMessageMapper.getWxOpenIdByTransac(entity);
    }

    @Override
    public Map<String, Object> sendTemplateMessage(SendTempMessage entity) throws Exception {
        CoreUser user = UserUtil.getUser();
        if (user == null) {
            String userName = PropertyUtil.getCommonProperty("lytDefLoginUser");
            user = userService.getUserByUsername(userName);
            SecurityInterceptor.tempUser.set(user);
        }

        Map<String ,Object>  result = new HashMap<>(16);
        /**开关打开标志*/
        String open = "Y";
        /**父类型为订单*/
        String ORDER = "order";
        /**父类型为优惠券记录*/
        String COUPINREC = "couponrec";
        /**父类型为离店报告*/
        String REPORT = "report";
        /**父类型为授权登录*/
        String APPLOGIN = "applogin";
        /**父类型为会员交易*/
        String TRANSAC = "transac";
        /**根据场景类型查询该类型下配置的模板*/
        PushSms pushSms = null;
        if (entity.getPushSceneId() != null) {
            pushSms = new PushSms();
            pushSms.setId(entity.getPushSceneId());
            pushSms = pushSmsService.queryById(pushSms);
        } else if (entity.getSceneType() != null) {
            pushSms = pushSmsService.queryPushSmsByType(entity.getSceneType());
        } else {
            pushSms = new PushSms();
            pushSms.setMpOpenFlag(entity.getMpOpenFlag());
            pushSms.setMpTempId(entity.getMpTempId());
            pushSms.setWxOpenFlag(entity.getWxOpenFlag());
            pushSms.setWxTempId(entity.getWxTempId());
        }
        /**判断该场景下小程序模板发送是否启用*/
        if (open.equals(pushSms.getMpOpenFlag())) {
            SendTempMessage params = new SendTempMessage();
            /**获取模板ID*/
            params.setTempRowId(pushSms.getMpTempId());
            params.setType("MP");
            params.setParentId(entity.getParentId());
            params.setParentType(entity.getParentType());
            /**获取data参数及page跳转页面参数*/
            SendTempMessage sendTempMessage = getParamsTest(params);
            /**获取发送小程序模板的参数*/
            String openId = "";
            SendTempMessage openParam = new SendTempMessage();
            openParam.setId(entity.getParentId());
            openParam.setAcctChannelType("MiniProgram");
            /**获取openId*/
            if (ORDER.equals(entity.getParentType())) {
                openId = sendTempMessageMapper.getWxOpenIdByOrder(openParam);
            } else if (COUPINREC.equals(entity.getParentType())) {
                openId = sendTempMessageMapper.getWxOpenIdByCoupRec(openParam);
            } else if (REPORT.equals(entity.getParentType())) {
                openId = sendTempMessageMapper.getWxOpenIdByDepartureReport(openParam);
            } else if (APPLOGIN.equals(entity.getParentType())) {
                openId = sendTempMessageMapper.getWxOpenIdByAppLogin(openParam);
            }  else if (TRANSAC.equals(entity.getParentType())) {
                openParam.setAcctChannelType("MiniProgram");
                openId = sendTempMessageMapper.getMpOpenIdByTransac(openParam);
            }
            /**如果formId为空并且openId不为空则从redis中获取该用户下的formId*/
            if (StringUtils.isBlank(entity.getFormId())) {
                String  messaheFormId = getMessageFormId(openId);
                entity.setFormId(messaheFormId);
            }
            /**如果openId和formId都不为空*/
            if (StringUtils.isNotBlank(openId) && StringUtils.isNotBlank(entity.getFormId())) {
                /*SendTempMessage params = new SendTempMessage();
                *//**获取模板ID*//*
                params.setTempRowId(pushSms.getMpTempId());
                params.setType("MP");
                params.setParentId(entity.getParentId());
                params.setParentType(entity.getParentType());
                *//**获取data参数及page跳转页面参数*//*
                SendTempMessage sendTempMessage = getParamsTest(params);*/
                sendTempMessage.setOpenId(openId);
                sendTempMessage.setFormId(entity.getFormId());
                /**发送小程序模板信息*/
                JSONObject mpJson = sendMpTemplate(sendTempMessage);
                LCLogger.info().withMessageKey("sendTemplateMessage").withMessage("发送小程序模板信息的返回参数" + mpJson).flush();
                /**发送成功返回true*/
                if (StringUtils.equals("ok",mpJson.getString("errmsg"))) {
                    result.put("MP",true);
                } else {
                    result.put("MP",false);
                    result.put("MPERROR",mpJson.getString("errmsg"));
                }
            } else {
                result.put("MP",false);
            }
        }
        /**判断该场景下微信模板发送是否启用*/
        if (open.equals(pushSms.getWxOpenFlag())) {
            String openId = "";
            SendTempMessage openParam = new SendTempMessage();
            openParam.setId(entity.getParentId());
            openParam.setAcctChannelType("OfficialAccount");
            /**获取openId*/
            if (ORDER.equals(entity.getParentType())) {
                openId =  sendTempMessageMapper.getWxOpenIdByOrder(openParam);
            } else if (COUPINREC.equals(entity.getParentType())) {
                openId = sendTempMessageMapper.getWxOpenIdByCoupRec(openParam);
            } else if (TRANSAC.equals(entity.getParentType())) {
                openId = sendTempMessageMapper.getWxOpenIdByTransac(openParam);
            }
            if (StringUtils.isNotBlank(openId)) {
                /**获取发送微信模板的参数*/
                SendTempMessage params = new SendTempMessage();
                /**获取模板id*/
                params.setTempRowId(pushSms.getWxTempId());
                params.setType("WeChat");
                params.setParentId(entity.getParentId());
                params.setParentType(entity.getParentType());
                /**获取参数data*/
                SendTempMessage sendTempMessage = getParamsTest(params);
                sendTempMessage.setOpenId(openId);
                JSONObject wxJson = sendWxTemplate(sendTempMessage);
                LCLogger.info().withMessageKey("sendTemplateMessage").withMessage("发送微信模板信息的返回参数" + wxJson).flush();
                if (StringUtils.equals("ok",wxJson.getString("errmsg"))) {
                    result.put("WX",true);
                } else {
                    result.put("WX",false);
                    result.put("WXERROR",wxJson.getString("errmsg"));
                }
            } else {
                result.put("WX",false);
            }
        }
        return result;
    }

    /**
     *@createdBy 闫有霞
     *@date 2018/12/14
     *@methods: getParams
     *@param: String tempRowId  模板记录ID
     *@return: sendTempMessage  发送模板信息参数对象
     *@description: 获取发送模板信息的参数
     **/
    public SendTempMessage getParamsTest(SendTempMessage entity) throws Exception {
        Long tempRowId = entity.getTempRowId();
        String type = entity.getType();
        Long parentId = entity.getParentId();
        /**根据模板记录ID 获取模板对象*/
        SendTempMessage sendTempMessage = new SendTempMessage();
        String WeChat = "WeChat";
        String MP = "MP";
        List<String> param = new ArrayList<>();
        Template template = new Template();
        template.setId(tempRowId);
        template = mpTemplateMapper.queryById(template);
        sendTempMessage.setTemplateId(template.getTemplateId());
        sendTempMessage.setMpTempTitle(template.getTitle());
        if (StringUtils.isNotBlank(template.getAttr3())) {
            String pageUrl = template.getAttr3() + "?id=" + parentId;
            sendTempMessage.setPageUrl(pageUrl);
        }

        Template finalTemplate = template;
        List<String> parameterList = new ArrayList<String>();
        parameterList.add(finalTemplate.getParameter1());
        parameterList.add(finalTemplate.getParameter2());
        parameterList.add(finalTemplate.getParameter3());
        parameterList.add(finalTemplate.getParameter4());
        parameterList.add(finalTemplate.getParameter5());
        parameterList.add(finalTemplate.getParameter6());

        /**判断模板信息类型获取appId 及 appSecret*/
        if (WeChat.equals(type)) {
            WxPlatform platform = new WxPlatform();
            platform.setId(Long.parseLong(template.getWxId()));
            platform = wxPlatformMapper.queryById(platform);
            sendTempMessage.setAppId(platform.getWx_app_id());
            sendTempMessage.setAppSecret(platform.getWx_app_secret());
            if (StringUtils.isNotBlank(template.getFirst())) {
                param.add(template.getFirst());
            }
            for (String parameterId : parameterList) {
                if (StringUtils.isNotBlank(parameterId)) {
                    TemTable temTable = new TemTable();
                    temTable.setId(Long.parseLong(parameterId));
                    TemTable record = tableMapper.queryById(temTable);
                    if ("LovTemplate".equalsIgnoreCase(record.getTable1())) {
                        String value = sendTempMessageMapper.queryValueByLov(record);
                        param.add(value);
                        continue;
                    }
                    if ("Transac".equalsIgnoreCase(record.getTable1())) {
                        // 交易Id
                        record.setId(parentId);
                        String value = sendTempMessageMapper.queryVauleByTransac(record);
                        if ("sub_type_cd".equalsIgnoreCase(record.getColumn1())) {
                            value = LovUtil.getLovName("LYT_TXN_SUB_TYPE", value);
                        }
                        if ("TXN_CHANNEL_CD".equalsIgnoreCase(record.getColumn1())) {
                            value = LovUtil.getLovName("LYT_TXN_CHANNEL", value);
                        }
                        if (StringUtils.isNum(value)) {
                            value = (int)Double.parseDouble(value) + "";
                        }
                        param.add(value);
                    }
                    if ("Member".equalsIgnoreCase(record.getTable1())) {
                        String value = sendTempMessageMapper.queryValueByLov(record);
                        param.add(value);
                        continue;
                    }
                    if ("PointResult".equals(record.getTable1())) {
                        record.setId(parentId);
                        String value;
                        if ("POINT_VALUE".equals(record.getColumn1())) {
                            value = sendTempMessageMapper.querySumVauleByPointResult(record);
                        } else {
                            value = sendTempMessageMapper.queryVauleByPointResult(record);
                        }
                        if (StringUtils.isNum(value)) {
                            value = (int)Double.parseDouble(value) + "";
                        }
                        param.add(value);
                    }
                    if ("PointBalances".equalsIgnoreCase(record.getTable1())) {
                        record.setId(parentId);
                        String value = null;
                        if ("AVAILABLE_POINTS".equalsIgnoreCase(record.getColumn1())) {
                            value = sendTempMessageMapper.querySumByPointBalances(record);
                            if (value == null) {
                                value = "0";
                            }
                        }
                        if (StringUtils.isNum(value)) {
                            value = (int)Double.parseDouble(value) + "";
                        }
                        param.add(value);
                    }
                }
            }
        } else if (MP.equals(type)) {
            for (String parameterId : parameterList) {
                if (StringUtils.isNotBlank(parameterId)) {
                    String[] data = parameterId.split(":");
                    TemTable record = new TemTable();
                    record.setColumn1(data[2]);
                    record.setTable1(data[1]);
                    if ("LovTemplate".equalsIgnoreCase(record.getTable1())) {
                        String value = sendTempMessageMapper.queryValueByLov(record);
                        param.add(value);
                        continue;
                    }
                    if ("Member".equalsIgnoreCase(record.getTable1())) {
                        record.setId(parentId);
                        String value = sendTempMessageMapper.queryVauleByMember(record);
                        param.add(value);
                        continue;
                    }
                    if ("Prod".equalsIgnoreCase(record.getTable1())) {
                        record.setId(parentId);
                        String value = sendTempMessageMapper.queryVauleByProd(record);
                        param.add(value);
                        continue;
                    }
                    if ("Transac".equalsIgnoreCase(record.getTable1())) {
                        // 交易Id
                        record.setId(parentId);
                        String value = sendTempMessageMapper.queryVauleByTransac(record);
                        if ("sub_type_cd".equalsIgnoreCase(record.getColumn1())) {
                            value = LovUtil.getLovName("LYT_TXN_SUB_TYPE", value);
                        }
                        if ("TXN_CHANNEL_CD".equalsIgnoreCase(record.getColumn1())) {
                            value = LovUtil.getLovName("LYT_TXN_CHANNEL", value);
                        }
                        if (StringUtils.isNum(value)) {
                            value = (int)Double.parseDouble(value) + "";
                        }
                        param.add(value);
                    }
                    if ("PointResult".equals(record.getTable1())) {
                        record.setId(parentId);
                        String value;
                        if ("POINT_VALUE".equals(record.getColumn1())) {
                            value = sendTempMessageMapper.querySumVauleByPointResult(record);
                        } else {
                            value = sendTempMessageMapper.queryVauleByPointResult(record);
                        }
                        if (StringUtils.isNum(value)) {
                            value = (int)Double.parseDouble(value) + "";
                        }
                        param.add(value);

                    }
                    if ("PointResult".equals(record.getTable1())) {
                        record.setId(parentId);
                        String value;
                        if ("POINT_VALUE".equals(record.getColumn1())) {
                            value = sendTempMessageMapper.querySumVauleByPointResult(record);
                        } else {
                            value = sendTempMessageMapper.queryVauleByPointResult(record);
                        }
                        if (StringUtils.isNum(value)) {
                            value = (int)Double.parseDouble(value) + "";
                        }
                        param.add(value);

                    }
                    if ("PointBalances".equalsIgnoreCase(record.getTable1())) {
                        record.setId(parentId);
                        String value = null;
                        if ("AVAILABLE_POINTS".equalsIgnoreCase(record.getColumn1())) {
                            value = sendTempMessageMapper.querySumByPointBalances(record);
                            if (value == null) {
                                value = "0";
                            }
                        }
                        if (StringUtils.isNum(value)) {
                            value = (int)Double.parseDouble(value) + "";
                        }
                        param.add(value);
                    }
                    // 互动记录
                    if (StringUtils.equals(record.getTable1(),"ActionInfo")) {
                        record.setId(parentId);
                        if (StringUtils.equals(record.getColumn1(),"prizeSetName")) {
                            record.setTable1("PrizeSet");
                            record.setColumn1("AWARD_NAME");
                        }
                        String value = sendTempMessageMapper.queryValueByActionInfo(record);
                        param.add(value);
                    }
                }
            }
        }
        if (StringUtils.isNotBlank(template.getRemark())) {
            param.add(template.getRemark());
        }
        sendTempMessage.setParams(param);
        return sendTempMessage;
    }


}

